package com.gxuwz.medical.web.servlet.menu;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gxuwz.medical.dao.MenuDao;
import com.gxuwz.medical.database.DbUtil;
import com.gxuwz.medical.domain.menu.Menu;
import com.gxuwz.medical.tools.JsonUtil;
import com.gxuwz.medical.tools.PageBean;
import com.gxuwz.medical.tools.ResponseUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class MenuListServlet extends HttpServlet {
	DbUtil dbUtil = new DbUtil();
	MenuDao menuDao = new MenuDao();

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		MenuList(request, response);
		System.out.println("菜单查询");
	}

	private void MenuList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("有啦");
		// 获取前台传来的查询数据
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String pid = request.getParameter("pid");
		String url = request.getParameter("url");
		System.out.println("id=" + id + "name=" + name + "pid=" + pid + "url=" + url);
		// 构造一个Student
		Menu menu = new Menu();
		if (id != null) {
			menu.setId(id);
			menu.setName(name);
			menu.setPid(pid);
			menu.setUrl(url);
		}

		String page = request.getParameter("page"); // 第几页
		String rows = request.getParameter("rows"); // 每页记录数

		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows)); // 得到PageBean
		Connection con = null;

		try {
			con = dbUtil.getCon();
			JSONObject result = new JSONObject();
			JSONArray jsonArray = JsonUtil.formatRsToJsoarray(menuDao.MenuList(con, pageBean, menu)); // 用JSONArray返回数据
			int total = menuDao.MenuCount(con, menu); // 获取学生总数
			result.put("rows", jsonArray); // 把JSONArray放入结果JSONObject中
			result.put("total", total); // 把total总数也放入结果JSONObject中
			ResponseUtil.write(response, result); // 把数据写入response
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
